import { useState, useRef, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import styles from './ChatInterface.module.css';
import { useSearchParams } from 'react-router-dom';

export default function Session() {
  const [searchParams] = useSearchParams();
  const sessionId = searchParams.get('sessionId');
  const navigate = useNavigate();

  const [currentSession, setCurrentSession] = useState(null);
  const [messages, setMessages] = useState([]);
  const [inputContent, setInputContent] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [tipMsg, setTipMsg] = useState(null);
  const messagesContainerRef = useRef(null);
  const email = searchParams.get('email');
  // 加载会话历史（仅此处排序：确保历史消息顺序正确）
  useEffect(() => {
    if (!sessionId) {
      setTipMsg('未找到会话ID，即将返回历史会话页');
      setTimeout(() => navigate('/chat-history'), 2000);
      return;
    }

    const fetchCurrentSession = async () => {
      try {
        const response = await fetch('http://localhost:5000/api/session/all');
        if (!response.ok) throw new Error(`请求失败: ${response.status} ${response.statusText}`);
        
        const allSessions = await response.json();
        const targetSession = allSessions.find(session => session.id === sessionId);
        
        if (!targetSession) {
          throw new Error('当前会话不存在或已被删除');
        }

        setCurrentSession(targetSession);
        // 仅加载历史消息时排序：时间早的在前，晚的在后
        const formattedMessages = targetSession.messages
          .map(msg => ({ ...msg, timestamp: new Date(msg.date) }))
          .sort((a, b) => a.timestamp - b.timestamp);
        setMessages(formattedMessages);

      } catch (err) {
        setTipMsg(err instanceof Error ? err.message : '加载会话失败，请重试');
        setTimeout(() => navigate('/chat-history'), 2000);
      }
    };

    fetchCurrentSession();
  }, [sessionId, navigate]);

  // 自动滚动到底部（不变）
  useEffect(() => {
    const container = messagesContainerRef.current;
    if (container) {
      requestAnimationFrame(() => {
        container.scrollTop = container.scrollHeight;
      });
    }
  }, [messages, isLoading]);

  // 保存消息到后端（不变）
  const saveMessageToBackend = async (message) => {
    try {
      const response = await fetch(`http://localhost:5000/api/session/message/add?sessionId=${message.sessionId}`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(message)
      });

      if (!response.ok) {
        const errorText = await response.text();
        throw new Error(`保存失败: ${response.status} - ${errorText}`);
      }

      return true;
    } catch (err) {
      console.error('保存消息到后端失败:', err);
      throw err;
    }
  };

  // 转换角色（不变）
  const convertRoleForAi = (role) => {
    switch(role) {
      case 'agent':
        return 'assistant';
      case 'user':
        return 'user';
      default:
        return 'user';
    }
  };

  // 发送消息逻辑（移除新增消息后的排序，直接插入最后）
  const handleSendMessage = async () => {
    const trimmedContent = inputContent.trim();
    if (!trimmedContent || isLoading || !sessionId || !currentSession) return;

    setIsLoading(true);
    const now = new Date();
    const messageDate = now.toISOString();
    const tempMessageId = `msg-${Date.now()}`;

    // 创建用户消息，直接追加到最后（不排序）
    const userMessage = {
      id: tempMessageId,
      role: 'user',
      content: trimmedContent,
      date: messageDate,
      timestamp: now,
      sessionId: sessionId,
      maskId: currentSession.mask.id.toString()
    };
    setMessages(prev => [...prev, userMessage]); // 直接插入最后
    setInputContent('');

    try {
      await saveMessageToBackend({
        role: 'user',
        content: trimmedContent,
        date: messageDate,
        sessionId: sessionId,
        maskId: currentSession.mask.id.toString()
      });

      const messagesForAi = [
        ...currentSession.mask.context.map(ctx => ({
          role: ctx.role,
          content: ctx.content
        })),
        ...messages.map(msg => ({ 
          role: convertRoleForAi(msg.role),
          content: msg.content 
        })),
        { role: 'user', content: trimmedContent }
      ];

      const aiResponse = await fetch('https://api.deepseek.com/chat/completions', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer sk-d230429752104f10b2ab1b8c24b6f813`
        },
        body: JSON.stringify({
          model: 'deepseek-chat',
          messages: messagesForAi,
          stream: false,
          temperature: 0.7
        })
      });

      if (!aiResponse.ok) {
        const aiError = await aiResponse.text();
        throw new Error(`AI请求失败: ${aiResponse.status} - ${aiError}`);
      }

      const aiData = await aiResponse.json();
      const aiContent = aiData.choices[0].message.content;
      const aiNow = new Date();
      const aiMessageDate = aiNow.toISOString();

      // 创建AI消息，直接追加到最后（不排序）
      const aiMessage = {
        id: `msg-${Date.now()}`,
        role: 'agent',
        content: aiContent,
        date: aiMessageDate,
        timestamp: aiNow,
        sessionId: sessionId,
        maskId: currentSession.mask.id.toString()
      };
      setMessages(prev => [...prev, aiMessage]); // 直接插入最后

      await saveMessageToBackend({
        role: 'agent',
        content: aiContent,
        date: aiMessageDate,
        sessionId: sessionId,
        maskId: currentSession.mask.id.toString()
      });

    } catch (err) {
      const errorContent = err instanceof Error ? `发送失败：${err.message}` : '发送失败，请稍后再试';
      const errorNow = new Date();
      
      const errorMessage = {
        id: `error-${Date.now()}`,
        role: 'agent',
        content: errorContent,
        date: errorNow.toISOString(),
        timestamp: errorNow,
        sessionId: sessionId,
        maskId: currentSession.mask.id.toString()
      };
      // 错误消息也直接追加到最后（不排序）
      setMessages(prev => [...prev, errorMessage]); // 直接插入最后
    } finally {
      setIsLoading(false);
    }
  };

  // 回车发送处理（不变）
  const handleKeyDown = (e) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSendMessage();
    }
  };

  // 加载状态显示（不变）
  if (isLoading && messages.length === 0) {
    return (
      <div className={styles.loadingContainer}>
        <div className={styles.spinner}></div>
        <p className={styles.loadingText}>加载会话中...</p>
      </div>
    );
  }

  return (
    <div className={styles.chatContainer}>
      <header className={styles.chatHeader}>
        <button 
          className={styles.backBtn}
          onClick={() => navigate('/HeroSection/select?email=${email}')}
          aria-label="返回历史会话"
        >
          ←
        </button>
        <div className={styles.headerTitle}>
          <span className={styles.maskName}>{currentSession?.mask.name || '未知面具'}</span>
          <span className={styles.topicSeparator}>·</span>
          <span className={styles.sessionTopic}>{currentSession?.topic || '新会话'}</span>
        </div>
        <div className={styles.headerPlaceholder}></div>
      </header>

      {tipMsg && (
        <div className={styles.tipBar}>
          <span className={styles.tipIcon}>⚠️</span>
          <span className={styles.tipText}>{tipMsg}</span>
          <button 
            className={styles.closeTipBtn}
            onClick={() => setTipMsg(null)}
          >
            ×
          </button>
        </div>
      )}

      <div className={styles.messagesContainer} ref={messagesContainerRef}>
        {messages.length === 0 && currentSession && (
          <div className={styles.emptyMessages}>
            <span className={styles.emptyIcon}>💬</span>
            <p className={styles.emptyText}>开始与{currentSession.mask.name}对话吧～</p>
            <p className={styles.emptySubText}>{currentSession.mask.context[0]?.content || '输入消息即可互动'}</p>
          </div>
        )}

        {messages.map((msg) => (
          <div 
            key={msg.id}
            className={`${styles.messageItem} ${
              msg.role === 'user' ? styles.userMessage : styles.agentMessage
            }`}
          >
            <div className={styles.messageAvatar}>
              {msg.role === 'user' 
                ? <span className={styles.userAvatar}>你</span>
                : (
                  currentSession?.mask.avatar && !['asd', 'asdf', 'asdfg', 'asdfgh'].includes(currentSession.mask.avatar)
                    ? <img src={currentSession.mask.avatar} alt={currentSession.mask.name} />
                    : <span className={styles.agentAvatar}>{currentSession.mask.name.charAt(0)}</span>
                )
              }
            </div>
            <div className={styles.messageContentWrapper}>
              {msg.role === 'agent' && (
                <div className={styles.messageSender}>{currentSession?.mask.name}</div>
              )}
              <div className={styles.messageContent}>{msg.content}</div>
              <div className={styles.messageTime}>
                {msg.timestamp.toLocaleTimeString('zh-CN', { 
                  hour: '2-digit', 
                  minute: '2-digit',
                  hour12: false 
                })}
              </div>
            </div>
          </div>
        ))}

        {isLoading && currentSession && (
          <div className={`${styles.messageItem} ${styles.agentMessage} ${styles.loadingMessage}`}>
            <div className={styles.messageAvatar}>
              {currentSession.mask.avatar && !['asd', 'asdf', 'asdfg', 'asdfgh'].includes(currentSession.mask.avatar)
                ? <img src={currentSession.mask.avatar} alt={currentSession.mask.name} />
                : <span className={styles.agentAvatar}>{currentSession.mask.name.charAt(0)}</span>
              }
            </div>
            <div className={styles.messageContentWrapper}>
              <div className={styles.messageSender}>{currentSession.mask.name}</div>
              <div className={styles.typingIndicator}>
                <span className={styles.typingDot}></span>
                <span className={styles.typingDot}></span>
                <span className={styles.typingDot}></span>
              </div>
            </div>
          </div>
        )}
      </div>

      <div className={styles.inputContainer}>
        <textarea
          className={styles.messageInput}
          value={inputContent}
          onChange={(e) => setInputContent(e.target.value)}
          onKeyDown={handleKeyDown}
          placeholder="输入消息（Shift+Enter换行）..."
          rows={3}
          disabled={isLoading || !currentSession}
        />
        <button
          className={styles.sendBtn}
          onClick={handleSendMessage}
          disabled={!inputContent.trim() || isLoading || !currentSession}
          aria-label="发送消息"
        >
          发送
        </button>
      </div>
    </div>
  );
}